package com.open.capacity.notice.provider.sms;

import java.io.IOException;
import java.util.Map;
import java.util.function.Consumer;

import com.open.capacity.notice.provider.NoticeTemplate;
import com.open.capacity.notice.provider.core.NoticeProvider;
import com.open.capacity.notice.provider.core.http.ThOkHttp3Template;
import com.open.capacity.notice.provider.core.http.interactive.req.ThRequest;
import com.open.capacity.notice.provider.sms.interactive.req.SendSmsRequest;
import com.open.capacity.notice.provider.sms.interactive.res.SendSmsResponse;

import cn.hutool.core.bean.BeanUtil;
import lombok.Data;
import lombok.RequiredArgsConstructor;

/**
 * 短信模板方法 
 *
 */
@Data
@RequiredArgsConstructor
public class SmsTemplate implements NoticeTemplate {

	private static final String CODE = NoticeProvider.SMS.getCode();

	private final ThOkHttp3Template thOkHttp3Template;

	private final SmsProperties smsProperties;

	private final AsyncSmsOperations asyncChannlOps = new AsyncSmsOperations(this);

	@SuppressWarnings("unchecked")
	public SmsProperties getProperties() {
		return smsProperties;
	}

	@SuppressWarnings("unchecked")
	public AsyncSmsOperations asyncOpsForChannel() {
		return asyncChannlOps;
	}

	@Override
	public boolean supports(String code) {
		return CODE.equals(code);
	}


	@Override
	public <REQ extends ThRequest> void sendText(REQ request, Consumer<Map<String,Object>> success,
			Consumer<IOException> failure) throws IOException {
		Consumer<SendSmsResponse> smsResponseConsumer = smsResponse -> {
			Map<String,Object> res = BeanUtil.beanToMap(smsResponse, false, true);
			res.put("flag", smsResponse.isSuccess());
			success.accept(res);
		};
		//短信只有文本类型,直接发送
		asyncChannlOps.sendText((SendSmsRequest)request, smsResponseConsumer, failure);
		
	}
	
	
}